package com.moyun.syssecurity.util;

import com.moyun.model.po.system.SysUserEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.stereotype.Component;

/**
 * <h3>org</h3>
 * <p>Security工具类</p>
 *
 * @author : ybx
 * @date : 2021-05-26 10:38:15
 **/
@Component
@Slf4j
@RequiredArgsConstructor
public class SecurityUtil {
    /**
     * SessionRegistry Session会话注册表
     * PersistentTokenRepository 持久令牌的Dao层 对应persistent_logins表 封装了基本的增删改操作
     */
    private final SessionRegistry sessionRegistry;
    private final PersistentTokenRepository persistentTokenRepository;

    /**
     * 说明
     * 类中 提及的用户user  均是 UserDetails接口的实现类  User类是springsecurity官方实现类
     *                                               SysUserEntity类是 我们自定义的实现类
     */

    /**
     * 从ThreadLocal获取其自己的SecurityContext，从而获取在Security上下文中缓存的登录用户
     */
    public static SysUserEntity getLoginUser() {
        SysUserEntity user = null;
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        if (auth.getPrincipal() instanceof UserDetails) {
            user = (SysUserEntity) auth.getPrincipal();
        }
        return user;
    }

}